package com.yc.web.servlets;

/**
 * @author zwei
 * @create 2024-06-24 19:05
 */

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;

@WebServlet("/FileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    // OSS 配置信息
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // OSS 外网节点或自定义域名
    private static final String accessKeyId = "LTAI5tMaMpqNrQHS5ums69Mr";
    private static final String accessKeySecret = "qrCGpsNCirvOSM8wrhnj97hSMO41qw";
    private static final String bucketName = "daiwei001";
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取上传的文件
        Part filePart = request.getPart("file");
        String fileName = filePart.getSubmittedFileName();
        InputStream fileContent = filePart.getInputStream();
        // 生成唯一的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String objectName = uuid + "_" + fileName;
        System.out.println(objectName);
        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(filePart.getSize());
        ossClient.putObject(bucketName, objectName, fileContent, metadata);
        ossClient.shutdown();
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
        System.out.println(url);
        HttpSession session=request.getSession();
        session.setAttribute("url",url);
    }
}

